package com.example.demo;

import com.example.demo.DAO.StudentDAO;
import com.example.demo.Service.StudentService;
import com.example.demo.Student.Student;

import java.io.*;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

@WebServlet("/student")
public class  StudentServlet extends HttpServlet {
    private StudentService studentService = new StudentService();

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       String pageNumStr = request.getParameter("pageNum");
        int pageNum = 1;
        if (pageNumStr != null && !pageNumStr.isEmpty()) {
        pageNum = Integer.parseInt(pageNumStr);
        }
        try {
        List<Student> studentList = studentList = studentService.getStudentByPage(pageNum);

        int totalCount = studentService.getTotalCount();
        int totalPages = (totalCount % StudentDAO.PAGE_SIZE == 0)? totalCount /
                StudentDAO.PAGE_SIZE : totalCount / StudentDAO.PAGE_SIZE + 1;
        request.setAttribute("studentList", studentList);
        request.setAttribute("pageNum", pageNum);
        request.setAttribute("totalPages", totalPages);
        request.getRequestDispatcher("/student_list.jsp").forward(request, response);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

}